package com.java110.mall.acct.cmd.payment;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.CmdContextUtils;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.account.AccountBondObjDto;
import com.java110.intf.acct.IAccountBondObjInnerServiceSMO;
import com.java110.utils.cache.CommonCache;
import com.java110.utils.cache.UrlCache;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.ListUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 保证金缴费
 */
@Java110Cmd(serviceCode = "payment.toQrBondFeePay")
public class ToQrBondFeePayCmd extends Cmd {

    @Autowired
    private IAccountBondObjInnerServiceSMO accountBondObjInnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        Assert.hasKeyAndValue(reqJson, "shopId", "未包含商铺编号");
    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        AccountBondObjDto accountBondObjDto = new AccountBondObjDto();
        accountBondObjDto.setObjId(reqJson.getString("shopId"));
        accountBondObjDto.setState(AccountBondObjDto.STATE_BUY_W);
        List<AccountBondObjDto> accountBondObjDtos = accountBondObjInnerServiceSMOImpl.queryAccountBondObjs(accountBondObjDto);
        if (ListUtil.isNull(accountBondObjDtos)) {
            throw new CmdException("未查询到店铺保证金");
        }
        String amount = accountBondObjDtos.get(0).getReceivableAmount();
        String createUserId = CmdContextUtils.getUserId(context);
        String shopId = reqJson.getString("shopId");
        String token = GenerateCodeFactory.getUUID();

        JSONObject payData = new JSONObject();
        payData.put("shopId", shopId);
        payData.put("business", "bondPay");
        payData.put("createUserId", createUserId);
        payData.put("money", amount);
        CommonCache.setValue("nativeQrcodePayment_" + token, payData.toJSONString(), CommonCache.PAY_DEFAULT_EXPIRE_TIME);
        JSONObject data = new JSONObject();
        String mallAppUrl = UrlCache.getMallAppUrl();
        mallAppUrl = mallAppUrl.endsWith("/") ? mallAppUrl : (mallAppUrl + "/");
        data.put("qrCode", mallAppUrl + "#/pages/order/qrCodeCashier?qrToken=" + token);
        data.put("money", amount);
        data.put("remark", "需要支付保证金为" + amount);
        context.setResponseEntity(ResultVo.createResponseEntity(data));

    }
}
